/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. 
 * See the GNU General Public License for more details.
 * 
 * Copyright (C) 2011 CellObject.net
 */
package net.cellobject.javacodeformatter.view;

import net.cellobject.javacodeformatter.model.IFormatterItem;
import net.cellobject.javacodeformatter.util.StringMatcher;

import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IMemento;

public class FormatterViewNameFilter extends ViewerFilter {
	private static final String TAG_PATTERN = "pattern";

	private static final String TAG_TYPE = "NameFilterInfo";

	private final StructuredViewer viewer;

	private String pattern = "";

	private StringMatcher matcher;

	public FormatterViewNameFilter(final StructuredViewer viewer) {
		this.viewer = viewer;
	}

	public String getPattern() {
		return pattern;
	}

	public void setPattern(final String newPattern) {
		final boolean filtering = matcher != null;
		if ( (newPattern != null) && (newPattern.trim().length() > 0)) {
			pattern = newPattern;
			matcher = new StringMatcher(pattern, true, false);
			if (!filtering) {
				viewer.addFilter(this);
			} else {
				viewer.refresh();
			}
		} else {
			pattern = "";
			matcher = null;
			if (filtering) {
				viewer.removeFilter(this);
			}
		}
	}

	@Override
	public boolean select(final Viewer viewer, final Object parentElement, final Object element) {
		return matcher.match( ((IFormatterItem)element).getName());
	}

	public void saveState(final IMemento memento) {
		if (pattern.length() == 0) {
			return;
		}
		final IMemento mem = memento.createChild(TAG_TYPE);
		mem.putString(TAG_PATTERN, pattern);
	}

	public void init(final IMemento memento) {
		final IMemento mem = memento.getChild(TAG_TYPE);
		if (mem == null) {
			return;
		}
		setPattern(mem.getString(TAG_PATTERN));
	}
}
